package com.newland.starpos.partner.service.function;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCache {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public boolean addSetIfAbsent(String key, String value){
        Objects.requireNonNull(key, "key is null");
        Objects.requireNonNull(value, "value is null");
        BoundSetOperations<String, String> opsForSet = redisTemplate.boundSetOps(key);
        Boolean ifPresent = opsForSet.isMember(value);

        if(ifPresent)
            return false;

        Long size = opsForSet.add(value);
        return true;
    }

    public void setString(String key, String value, long l, TimeUnit timeUnit){
        Objects.requireNonNull(key, "key is null");
        Objects.requireNonNull(value, "value is null");
        ValueOperations opsForValue = redisTemplate.opsForValue();
        opsForValue.set(key, value, l, timeUnit);
    }

    public String getString(String key){
        Objects.requireNonNull(key, "key is null");
        ValueOperations opsForValue = redisTemplate.opsForValue();
        return String.valueOf(opsForValue.get(key));
    }

    public void delete(String key) {
        Objects.requireNonNull(key, "key is null");
        redisTemplate.delete(key);
    }

    public long increment(String key, long i) {
        return redisTemplate.opsForValue().increment(key, i);
    }

    public void expire(String key, long l, TimeUnit timeUnit) {
        redisTemplate.expire(key, l, timeUnit);
    }
}
